package mylab.starters.oss.config.qiniu;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.RequiredArgsConstructor;
import mylab.starters.oss.OssRule;
import mylab.starters.oss.config.OssAutoConfiguration;
import mylab.starters.oss.config.OssProperties;
import mylab.starters.oss.support.qiniu.QiniuOssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@AutoConfigureAfter(OssAutoConfiguration.class)
@ConditionalOnProperty(value = QiniuAutoConfiguration.PREFIX, havingValue = "true")
public class QiniuAutoConfiguration {
    static final public String PREFIX = OssProperties.PREFIX + ".qiniu.enabled";
    private final OssProperties ossProperties;

    @Bean
    @ConditionalOnMissingBean(com.qiniu.storage.Configuration.class)
    public com.qiniu.storage.Configuration qnConfiguration() {
        return new com.qiniu.storage.Configuration(Zone.autoZone());
    }

    @Bean
    public Auth auth() {
        OssProperties.QiniuOssProperties qiniu = ossProperties.getQiniu();
        return Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
    }

    @Bean
    @ConditionalOnBean(com.qiniu.storage.Configuration.class)
    public UploadManager uploadManager(com.qiniu.storage.Configuration cfg) {
        return new UploadManager(cfg);
    }

    @Bean
    @ConditionalOnBean(com.qiniu.storage.Configuration.class)
    public BucketManager bucketManager(com.qiniu.storage.Configuration cfg) {
        return new BucketManager(auth(), cfg);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({Auth.class, UploadManager.class, BucketManager.class, OssRule.class})
    public QiniuOssTemplate qiNiuCloudTemplate(Auth auth, UploadManager uploadManager, BucketManager bucketManager, OssRule ossRule) {
        return new QiniuOssTemplate(ossProperties.getQiniu(), ossRule, auth, uploadManager, bucketManager);
    }
}
